<template>
  <el-card shadow="never" class="border-1">
    <div id="myEchart" style="width: 100%; height: 300px"></div>
  </el-card>
</template>

<script setup>
import * as echarts from "echarts";
import { onMounted, onUnmounted, reactive } from "vue";
import { getCategories } from "@/api/frontend/category";
import { toRaw } from "@vue/reactivity";

let myEchart = echarts;
let articleCountData = reactive([]);
onMounted(() => {
  getCategories().then((e) => {
    if (e.success) {
      let categoryData = e.data.categoryList;
      let Data = [];
      for (let item of categoryData) {
        const list_item = { value: item.count, name: item.name };
        Data.push(list_item);
      }
      articleCountData.value = Data;
      initChart();
    }
  });
});

onUnmounted(() => {
  myEchart.dispose;
});

function initChart() {
  let echart = myEchart.init(
    document.getElementById("myEchart"),
    "purple-passion"
  );
  echart.setOption({
    title: {
      text: "文章分类占比",
      left: "center",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      top: "10%",
      left: "center",
    },
    series: [
      {
        name: "分类数量",
        type: "pie",
        radius: ["40%", "60%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: articleCountData.value,
      },
    ],
  });
  // 为窗口加上宽度变化事件，当宽高发生改变时，调用echarts的resize()方法，调整图表尺寸
  window.addEventListener("resize", function () {
    echart.resize();
  });
}
</script>
<style scoped>
</style>
